import { useRef } from 'react';
import { PlusOutlined, ReloadOutlined, SettingOutlined, EditOutlined } from '@ant-design/icons';
import { Button as AButton, Space as ASpace, Modal as AModal } from 'antd';
import { ProTable as PProTable } from '@ant-design/pro-components';

import { type DeviceGraph, deviceGraphListApi, deviceGraphDeleteApi } from '@/api/deviceGraphApi';
import { useRouter } from '@/hooks/useRouter';
import { TableLocalePresets } from '@/utils/tableUtils';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

import GraphEdit from './edit';
import GraphView from './view';

export { GraphEdit, GraphView };

/**
 * 设备分组管理页面组件
 * 提供设备分组的创建、编辑、删除等功能，支持批量操作
 */
const DeviceGroupManager = () => {
  // 路由导航
  const { navigate } = useRouter();

  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  /**
   * 获取设备组态图列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // setLoading(true); // 预留用于后续功能

      // 处理分页参数
      const requestParams = {
        ...params,
        pageNum: params.current,
        pageSize: params.pageSize,
      };

      const res = await deviceGraphListApi(requestParams);

      if (res.success) {
        const responseData = res.data;

        // 处理不同的响应数据结构
        if (Array.isArray(responseData)) {
          // 如果直接返回数组
          return {
            success: true,
            data: responseData,
            total: responseData.length,
          };
        } else if (responseData && typeof responseData === 'object') {
          // 如果返回对象结构
          const listData = responseData as API.ListType<DeviceGraph>;
          return {
            success: true,
            data: listData.records ?? [],
            total: listData.total ?? 0,
          };
        }

        return {
          success: true,
          data: [],
          total: 0,
        };
      } else {
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取设备分组列表失败:', error);
      window.$message.error('获取设备分组列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    } finally {
      // setLoading(false); // 预留用于后续功能
    }
  };

  /**
   * 新增设备组态图
   */
  const handleAdd = () => {
    navigate('/device/graph/edit/-1');
  };

  /**
   * 删除单个设备分组
   * @param record 设备分组记录
   */
  const handleDelete = async (record: DeviceGraph) => {
    AModal.confirm({
      title: '确认删除',
      content: `确定要组态图"${record.name}"吗？删除后不可恢复。`,
      okText: '确定删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await deviceGraphDeleteApi(record);
          if (res.success) {
            window.$message.success('删除成功');
            actionRef.current?.reload();
          } else {
            window.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          window.$message.error('删除失败，请重试');
        }
      },
    });
  };

  /**
   * 导出单个设备组态图
   * @param record 设备组态图记录
   */
  const handleExport = (record: DeviceGraph) => {
    const contentString = record.content;
    const filename = record.name || `graph_${record.id}`;

    if (!contentString || contentString === '{}' || contentString === '[]') {
      window.$message.error('该组态图没有内容可导出');
      return;
    }

    try {
      const parsedContent = JSON.parse(contentString);
      const prettyContent = JSON.stringify(parsedContent, null, 2);
      const blob = new Blob([prettyContent], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${filename}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (e) {
      window.$message.error('内容格式错误，无法导出');
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<DeviceGraph>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      search: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      search: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 220,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => {
              const id = record.id;
              if (!record.id) {
                window.$message.error('组态图ID不存在，无法查看详情');
                return;
              }
              // navigate(`/device/graph/view/${record.id}`);
              if (id && id !== '-1') {
                const path = `/device/graph/view/${id}`;
                const isHashRouter = window.location.href.includes('#');
                const url = isHashRouter ? `#${path}` : path;
                window.open(url, '_blank');
              } else {
                window.$message.warning('请先保存组态图再进行预览');
              }
            }}
          >
            查看
          </AButton>
          <AButton type="link" size="small" onClick={() => handleExport(record)}>
            导出
          </AButton>
          <AButton
            type="link"
            size="small"
            onClick={() => {
              if (!record.id) {
                window.$message.error('组态图ID不存在，无法编辑');
                return;
              }
              navigate(`/device/graph/edit/${record.id}`);
            }}
          >
            编辑
          </AButton>
          <AButton type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </AButton>
        </ASpace>
      ),
    },
  ];

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <div className="page-main-title">组态图</div>
        <div className="page-sub-title">组态图</div>
      </div>

      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="w-full">
            <PProTable<DeviceGraph>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchData}
              rowKey="id"
              search={{
                span: 6,
                labelWidth: 'auto',
                defaultCollapsed: false,
              }}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton key="add" type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                  新增组态图
                </AButton>,
              ]}
              locale={TableLocalePresets.product(actionRef)}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default DeviceGroupManager;
